package com.example.springdemo.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DatabaseTestService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @PostConstruct
    public void testDatabaseConnection() {
        try {
            log.info("测试数据库连接...");
            
            // 测试基本连接
            String result = jdbcTemplate.queryForObject("SELECT 1", String.class);
            log.info("数据库连接测试结果: {}", result);
            
            // 检查表是否存在
            List<Map<String, Object>> tables = jdbcTemplate.queryForList(
                "SHOW TABLES LIKE 'biz_exception_retry_record'"
            );
            log.info("biz_exception_retry_record 表存在: {}", !tables.isEmpty());
            
            if (!tables.isEmpty()) {
                // 检查表结构
                List<Map<String, Object>> columns = jdbcTemplate.queryForList(
                    "DESCRIBE biz_exception_retry_record"
                );
                log.info("表结构:");
                for (Map<String, Object> column : columns) {
                    log.info("字段: {} - 类型: {} - 是否为空: {} - 默认值: {}", 
                        column.get("Field"), 
                        column.get("Type"), 
                        column.get("Null"), 
                        column.get("Default"));
                }
                
                // 检查表中是否有数据
                Integer count = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) FROM biz_exception_retry_record", 
                    Integer.class
                );
                log.info("表中记录数: {}", count);
            }
            
        } catch (Exception e) {
            log.error("数据库连接测试失败", e);
        }
    }
} 